package com.ruoyi.system.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类
 *
 * @author ruoyi
 */
@Configuration
public class RabbitMQConfig {

    // 排班通知队列
    public static final String SCHEDULE_NOTIFICATION_QUEUE = "schedule.notification.queue";
    public static final String SCHEDULE_NOTIFICATION_EXCHANGE = "schedule.notification.exchange";
    public static final String SCHEDULE_NOTIFICATION_ROUTING_KEY = "schedule.notification";

    /**
     * 创建排班通知队列
     */
    @Bean
    public Queue scheduleNotificationQueue() {
        return QueueBuilder.durable(SCHEDULE_NOTIFICATION_QUEUE).build();
    }

    /**
     * 创建排班通知交换机
     */
    @Bean
    public DirectExchange scheduleNotificationExchange() {
        return new DirectExchange(SCHEDULE_NOTIFICATION_EXCHANGE);
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding scheduleNotificationBinding() {
        return BindingBuilder
                .bind(scheduleNotificationQueue())
                .to(scheduleNotificationExchange())
                .with(SCHEDULE_NOTIFICATION_ROUTING_KEY);
    }

    /**
     * JSON消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 配置监听器容器工厂
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(messageConverter());
        return factory;
    }

    /**
     * 配置RabbitTemplate
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }
}
